package com.hxzy.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxzy.common.constans.RedisConstans;
import com.hxzy.entity.Contamer;
import com.hxzy.service.ContamerService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
 * @Author wy
 * @Description 会员每天统计注册人员个数
 * @Date 2023/7/17 14:29
 * @Version 1.0
 */
@Log4j2
@EnableScheduling
@Configuration
public class ContamerTaskConfig {
    @Autowired
    private ContamerService contamerService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 每天0点做任务
     */
    @Scheduled(cron = "0 0 0 * * ? ")
    public void taskCorn(){
        task();
    }

    private void task(){
        String key=DateUtil.format(new Date(),"yyyyMM");
        //contamer:202307
        String redisKey= RedisConstans.getRedisKey(RedisConstans.CONTAMER_HASH_KEY,key);
        //前一天的数据统计
        Date yesterday= DateUtil.offsetDay(new Date(),-1);

        //前一天开始
        Date begin=DateUtil.beginOfDay(yesterday);
        //前一天结束
        Date end=DateUtil.endOfDay(yesterday);

        LambdaQueryWrapper<Contamer>  queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.between(Contamer::getCreateTime,begin,end);
        long count = this.contamerService.count(queryWrapper);

        //写入到redis中
        int day = DateUtil.dayOfMonth(yesterday);
        this.redisTemplate.opsForHash().put(redisKey,day+"",count);
        log.info("计算前一天"+yesterday.toString()+"会员注册任务完成");
    }

}
